<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/12 13:35
 * Desc:
 */
class Service_Api_Outdoor extends Contract_Api_Product
{
    /**
     * 类型ID
     */
    const TYPE_ID = 114;

    public function search(array $params = array()): array
    {
        $mid     = Arr::get($params, 'mid', '');
        $page     = Arr::get($params, 'page', 1);
        $pagesize = Arr::get($params, 'pagesize', 10);

        $data = Model_Outdoor::search_result($params, '', $page, $pagesize);
        if (!empty($data['list'])) {

            $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance(self::TYPE_ID, array('mid' => $mid));
            $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);
            foreach ($data['list'] as &$v) {
                if(isset($uni_img[$v['id']])){
                    $v['litpic'] = $uni_img[$v['id']];
                }
                $time_arr = array();
                foreach ($v['periods'] as $key => $period) {
                    $time_arr[] = date('m-d', $period['day']);
                    if ($key == 1) {
                        break;
                    }
                }
                $v['startDay']      = isset($v['periods'][0]) ? date("m月d日", $v['periods'][0]['day']) : '';
                $v['starttime_str'] = implode('、', $time_arr);
                $v['starttime_str'] .= count($v['periods']) > 2 ? '等' : '';
                $v['date']          = Model_Api_V2_Outdoor::format_date($v);
                $v['litpic']        = $this->img_url($v['litpic'], 340, 340);
                $v['marketing_strategy'] = $marketing_strategy->get_support_application($v['id']);
            }
        }
        return $data;
    }

    public function info(array $params = array()): array
    {
        $id = Arr::get($params, 'id');

        $info = DB::select()
            ->from('outdoor')
            ->where('id', '=', $id)
            ->execute()
            ->current();
        if (!$info) {
            throw new Exception('产品未找到');
        }

        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID,2);
        if(isset($uni_img['litpic'][$info['id']])){
            $info['litpic'] = $uni_img['litpic'][$info['id']];
            $info['piclist'] = $uni_img['piclist'][$info['id']];
        }
        $seckill_id = Arr::get($params, 'seckill_id', 0);
        $mid        = Arr::get($params, 'mid', '');

        $info['series']        = St_Product::product_series($info['id'], self::TYPE_ID);
        $info['piclist']       = $this->pic_list_url($info['piclist']);
        $info['litpic']        = $this->img_url($info['litpic'], 750, 750);
        $info['iconlist']      = $this->icons($info['iconlist']);
        $info['product_video'] = $info['product_video'] ? $this->img_url((explode('|', $info['product_video'])[0])) : '';
        $info['video_litpic']  = $info['product_video'] ? $this->img_url($info['litpic'], 375, 200) : '';
        $info['linedoc']       = unserialize($info['linedoc']);

        if(empty($info['linedoc']['path'])){
            $info['linedoc']['path']=null;
        }
        $info['attrlist']      = Model_Outdoor_Attr::get_attrs($info['attrid']);

        $info['commentnum']   = Model_Comment::get_comment_num($info['id'], self::TYPE_ID); //评论次数
        $info['satisfyscore'] = St_Functions::get_satisfy(self::TYPE_ID, $info['id'], $info['satisfyscore'], array('suffix' => ''));
        $info['sellnum']      = Model_Member_Order_statistic::get_sell_num(self::TYPE_ID, $info['id']) + intval($info['bookcount']);
        $info['price']        = Model_Outdoor::get_minprice($info['id'], array('info' => $info));

        // 会员折扣
        $info['discount_min_price'] = $mid ? Model_Api_V2_Discount::get_discount($mid, self::TYPE_ID, $id, $info['price']) : '';

        // 处理文档地址
        if (isset($info['linedoc']['path'][0])) {
            $info['linedoc']['path'][0] = Model_Api_V2_System::reorganized_resource_url($info['linedoc']['path'][0]);
        }
        $info['startcity_name']  = Model_Startplace::start_city($info['startcity']);
        $info['finaldest_name']  = Model_Destinations::getKindnameList($info['finaldestid']);
        $info['bookstatus']      = Model_Outdoor::get_book_status($info);
        $info['bookstatus_name'] = Model_Outdoor::get_bookstatus_name($info['bookstatus']);

        // 集合地点
        $info['gather_pos_arr'] = Model_Outdoor::get_gather_pos_arr($info['gather_pos_ids']);
        $pos_name               = array();
        if (!empty($info['gather_pos_arr'])) {
            $pos_name = Arr::pluck($info['gather_pos_arr'], 'name');
        }
        $info['gather_address'] = implode('、', $pos_name);

        //供应商
        if ($info['supplierlist']) {
            $supplier_shop_service = new Service_Api_Supplier_Shop();
            $info['suppliers']     = $supplier_shop_service->get_shop_info($info['supplierlist']);
        }

        //导游
        if ($info['guideid']) {
            $info['guide'] = Model_Outdoor::get_guide($info['guideid']);
        }

        // 获取活动行程
        $info['content'] = Model_Api_V2_Outdoor::get_detail_content(array('productinfo' => $info, 'typeid' => self::TYPE_ID));

        // 处理内容
        $info['bookcontent'] = $this->content_add_domain($info['bookcontent']);
        $info['feeinclude']  = $this->content_add_domain($info['feeinclude']);
        $info['notice']      = $this->content_add_domain($info['notice']);

        // 价格循环
        $periods = Model_Outdoor::get_bookable_periods($info['id'], 30, $seckill_id);
        foreach ($periods as &$perval) {
            $perval['start_day'] = date("m-d", strtotime($perval['date']));
            $perval['end_day']   = date("m-d", strtotime($perval['end_date']));
            $perval['period']   = Model_Outdoor::get_period($info['id'], $perval['day'], $info);
            $perval['price']    = Currency_Tool::price($perval['price']);
            $perval['profit']   = Currency_Tool::price($perval['profit']);
        }

        return array(
            'info' => $info,
            'periods' => $periods,
            'fields' => Model_Api_V2_Outdoor::tourer_fields($info['id'], $info['gather_pos_ids']),
        );
    }

    public function query_condition(): array
    {
        $data = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量优先'),
                array('id' => 4, 'name' => '人气推荐')
            ),
            'price' => array('name' => '价格', 'child' => array()),
        );

        // 价格
        $data['price']['child'] = DB::select()->from('outdoor_pricelist')->execute()->as_array();
        foreach ($data['price']['child'] as &$row) {
            if ($row['min'] != '' && $row['max'] != '') {
                $row['name'] = Currency_Tool::symbol() . $row['min'] . '-' . Currency_Tool::symbol() . $row['max'];
            } else if ($row['min'] == '') {
                $row['name'] = Currency_Tool::symbol() . $row['max'] . '以下';
            } else if ($row['max'] == '') {
                $row['name'] = Currency_Tool::symbol() . $row['min'] . '以上';
            }
        }

        // 属性
        $data['attribute'] = Model_Api_V2_Outdoor::get_attribute_by_pid();
        foreach ($data['attribute'] as &$item) {
            $item['child'] = Model_Api_V2_Outdoor::get_attribute_by_pid($item['id']);
        }

        // 天数
        $data['days'] = Taglib_Outdoor::day_list(array());

        return $data;
    }

    public function create_order(array $params = array()): array
    {
        $mid         = $params['mid'];
        $member_info = $params['member_info'];
        $product_id  = $params['product_id'];
        $suit_id     = $params['suit_id'];
        $use_date    = $params['use_date'];
        $source      = $params['source'];
        $ding_num    = Arr::get($params, 'ding_num', 0);
        $child_num   = Arr::get($params, 'childnum', 0);
        $remark      = Arr::get($params, 'remark', '');

        $outdoor = DB::select()
            ->from('outdoor')
            ->where('id', '=', $product_id)
            ->and_where('status', '=', 3)
            ->execute()
            ->current();
        if (empty($outdoor)) {
            throw new Exception('产品不存在或未上架');
        }

        // 提前下单日期检查
        $line_before    = $outdoor['linebefore'];
        $is_line_before = $outdoor['islinebefore'];
        if ($is_line_before > 0 && $line_before > 0) {
            $line_before_day = date("Y-m-d", strtotime("+{$line_before} day"));
            if (strtotime($use_date) < strtotime($line_before_day)) {
                throw new Exception('需提前' . $line_before . '天预订');
            }
        }

        $suit_info = Model_Outdoor_Suit::suit_info($suit_id);
        if (empty($suit_info)) {
            throw new Exception('套餐不存在');
        }

        $price_info = Model_Outdoor::get_suit_date_price($suit_id, $use_date);
        if (!$price_info) {
            throw new Exception('套餐未报价');
        }

        $seckill_id = Arr::get($params, 'seckill_id', 0);
        if ($seckill_id > 0) {
            $status = Model_Seckill::get_seckill_num($seckill_id, $mid);
            if (!$status) {
                throw new Exception('已超出活动限制次数');
            }
        }

        // 检查游客
        $tourist = Arr::get($params, 'tourist', '');
        $tourist = $tourist ? json_decode($tourist, true) : '';
        if (Model_Sysconfig::get_configs(0, 'cfg_plugin_outdoor_usetourer', true) == 1 && empty($tourist)) {
            throw new Exception('请添加游客');
        }

        // 检查联系人
        $link_info = Arr::get($params, 'link_info', '');
        $link_info = $link_info ? json_decode($link_info, true) : '';
        if (empty($link_info)) {
            throw new Exception('请填写联系人信息');
        }

        $depart_date = date('Y-m-d', strtotime($use_date) + ((max($outdoor['lineday'], 1)) - 1) * 24 * 3600);
        $order       = array(
            'webid' => 0,
            'addtime' => time(),
            'typeid' => self::TYPE_ID,
            'ordersn' => St_Product::get_ordersn(self::TYPE_ID),
            'litpic' => $outdoor['litpic'],
            'productaid' => $outdoor['aid'],
            'productname' => $outdoor['title'],
            'suit_name' => $suit_info['title'],
            'dingnum' => $ding_num,
            'childnum' => $child_num,
            'oldprice' => 0,
            'oldnum' => 0,
            'need_confirm' => $suit_info['need_confirm'],
            'status' => $suit_info['need_confirm'] ? 0 : 1,
            'auto_close_time' => $suit_info['auto_close_time'] ? $suit_info['auto_close_time'] + time() : 0,
            'auto_confirm_time' => $suit_info['auto_confirm_time'] ? $suit_info['auto_confirm_time'] + time() : 0,
            'productautoid' => $product_id,
            'suitid' => $suit_id,
            'source' => $source,
            'usedate' => $use_date,
            'departdate' => $depart_date,
            'linkman' => $link_info['name'],
            'linktel' => $link_info['phone'],
            'linkemail' => empty($link_info['linkemail']) ? '' : $link_info['linkemail'],
            'remark' => $remark,
            'memberid' => $mid,
            'jifenbook' => $outdoor['jifenbook_id'],
            'jifencomment' => ($comment = Model_Jifen::get_used_jifencomment(self::TYPE_ID)) ? $comment['value'] : 0,
            'refund_restriction' => $suit_info['refund_restriction'],
            'people4_num' => 0,
            'people4_price' => 0,
            'people5_num' => 0,
            'people5_price' => 0,
            'people6_num' => 0,
            'people6_price' => 0,
        );

        // 自动关闭订单时间
        $auto_close_time = $suit_info['auto_close_time'] ?: 0;
        if ($auto_close_time) {
            $order['auto_close_time'] = $auto_close_time + time();
        }
        // 待确认时限
        $auto_confirm_time = $suit_info['auto_confirm_time'] ?: 0;
        if ($auto_confirm_time) {
            $order['auto_confirm_time'] = $auto_confirm_time + time();
        }
        //自动退款时限
        $use_date=trim($params['use_date']);
        $no_confirm_refund = $suit_info['no_confirm_refund'] ?: 0;
        if ($no_confirm_refund) {
            $order['no_confirm_refund'] = strtotime($use_date . ' +1 day') -  $no_confirm_refund ;
        }


        if ($seckill_id > 0) {
            $seckill                                = DB::select()->from('seckill')->where("id={$seckill_id}")->execute()->current();
            $seckill['suit_original_adult_price']   = $price_info['price'];
            $seckill['suit_original_child_price']   = $price_info['childprice'];
            $seckill['suit_original_old_price']     = 0;
            $seckill['suit_original_people4_price'] = 0;
            $seckill['suit_original_people5_price'] = 0;
            $seckill['suit_original_people6_price'] = 0;

            // 更新订单信息
            $order['paytype'] = 1;
            $order['pay_way'] = 1;
            $order['dingjin'] = 0;
        } else {
            $order['paytype'] = $suit_info['paytype'];
            $order['pay_way'] = $suit_info['pay_way'];
            $order['dingjin'] = $suit_info['paytype'] == 2 ? $suit_info['dingjin'] : 0;
        }

        $order['price']      = $price_info['price'];
        $order['childprice'] = $price_info['childprice'];

        // 合同判断
        if ($outdoor['contractid']) {
            $contract = Model_Contract::get_contents($outdoor['contractid'], self::TYPE_ID);
            if ($contract) {
                $order['contract_id'] = $outdoor['contractid'];
            }
        }

        //积分抵现
        if ($params['needjifen'] && $order['memberid']) {
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($outdoor['jifentprice_id'], self::TYPE_ID, $params['needjifen'], $member_info);
            if ($member_info && $jifentprice && $jifentprice <= $order['price']) {
                $order['jifentprice'] = $jifentprice;
                $order['usejifen']    = 1;
                $order['needjifen']   = $params['needjifen'];
            } else {
                throw new Exception(__('积分抵现不可用'));
            }
        }

        //优惠券
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $order);
        }

        //秒杀过来的就添加关联订单
        if (!empty($seckill)) {
            Model_Seckill::add_seckill_order($order, $seckill);
        }

        /*附加信息*/
        $card_tourist_id = Arr::get($params, 'card_tourist_id', '');
        $extend_params   = array(
            'member_card_id' => Arr::get($params, 'member_card_id', ''),
            'card_tourist_id' => implode(',', array_filter(explode(',', $card_tourist_id))),
        );

        // 秒杀不使用会员折扣
        if ($seckill_id) {
            $extend_params['use_member_discount'] = false;
        }

        //写入订单
        $result = Model_Api_V2_Order::add_order($order, 'Model_Outdoor', $extend_params);
        if (!$result['status']) {
            throw new Exception($result['msg']);
        }

        // 优惠券
        if (!empty($coupon_check)) {
            Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
        }

        $order_info = Model_Member_Order::order_info($order['ordersn']);

        $envelope_member_id = Arr::get($params, 'envelope_member_id', 0);
        if ($envelope_member_id) {
            if (St_Functions::is_normal_app_install('red_envelope')) {
                Model_Order_Envelope::order_use_envelope($envelope_member_id, $order['ordersn'], self::TYPE_ID, $mid);
            }
        }

        // 添加游客
        if (!empty($tourist)) {
            Model_Outdoor_Tourer::add_tourer($order_info['id'], $tourist, $order['memberid']);
        }

        //订单结算信息表数据更新
        Model_Member_Order_Compute::update($order['ordersn']);

        // 事件
        Hook::trigger('order_created', $order_info);

        $order_info['orderid'] = $order_info['id'];
        $filter_keys           = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }

    use Trait_Api_Outdoor;
}